package page

import (
	"blog/model"
	"blog/service/data"
	"sync"

	"github.com/gin-gonic/gin"
)

type IndexPageService struct {
	postDataService *data.PostDataService
	linkDataService *data.LinkDataService
	tagDataService  *data.TagDataService
}

func NewIndexPageService() *IndexPageService {
	return &IndexPageService{
		postDataService: &data.PostDataService{},
		linkDataService: &data.LinkDataService{},
		tagDataService:  &data.TagDataService{},
	}
}

// GetIndexPageData 获取首页数据（页面逻辑）
func (s *IndexPageService) GetIndexPageData(ctx *gin.Context, pageId int64) (*IndexPageReturnData, error) {
	var result IndexPageReturnData
	var wg sync.WaitGroup
	var errChan = make(chan error, 3)

	wg.Add(3)

	// 获取链接列表
	go func() {
		links, err := s.linkDataService.GetLinks(ctx, 0)
		if err != nil {
			errChan <- err
		} else {
			result.LinkList = links
		}
		wg.Done()
	}()

	// 获取标签列表
	go func() {
		result.TagList = s.tagDataService.GetTagList(ctx, "rand", model.TagListPageSize)
		wg.Done()
	}()

	// 获取文章列表
	go func() {
		postList := s.postDataService.GetPostListForIndex(ctx, pageId, model.IndexPageSize, 0, false)
		result.PostList = postList
		wg.Done()
	}()

	wg.Wait()
	close(errChan)

	// 检查是否有错误
	select {
	case err := <-errChan:
		return nil, err
	default:
		return &result, nil
	}
}

// IndexPageReturnData 首页返回数据结构
type IndexPageReturnData struct {
	PostList model.PostListData `json:"posts"` // 文章列表
	LinkList []model.LinkData   `json:"links"` // 外链列表
	TagList  []model.TagData    `json:"tags"`  // 标签列表
}
